package net.daum.webtoon.android;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import net.daum.webtoon.android.jibx.data.FileManager;
import net.daum.webtoon.android.jibx.data.ImageItem;
import net.daum.webtoon.android.jibx.data.ToonItem;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ListView;

public class MainActivity2 extends Activity {

	public static String TAG = MainActivity2.class.getSimpleName();
	private WebView mView;
	private ListView mListView;
	public static ToonItem mToonItem;
	private String mToonName;
	private boolean isFirst = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2);
		mToonName = getIntent().getStringExtra(ContentListActivity.TOONNAME);
		mView = (WebView) findViewById(R.id.main_view2);
		mView.setWebViewClient(new WebViewClientClass());
		mView.getSettings().setJavaScriptEnabled(true);
		mView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
		mView.getSettings().setLoadsImagesAutomatically(false);
		mView.loadUrl(("http://cartoon.media.daum.net/webtoon/viewer/" + mToonName.trim()).trim());
		mView.setVisibility(View.INVISIBLE);
		mListView = (ListView) findViewById(R.id.list_view);
		mToonItem = new ToonItem();
		mToonItem.images = new ArrayList<ImageItem>();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void xmlOnClick(View v) {

	}

	private class WebViewClientClass extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			if (url.equalsIgnoreCase(("http://cartoon.media.daum.net/webtoon/viewer/" + mToonName.trim()).trim())) {
				view.loadUrl("http://cartoon.media.daum.net/webtoon/viewer_images.js?webtoon_episode_id=" + mToonName.trim());
				isFirst = true;
			} else if (isFirst) {
				view.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
				view.stopLoading();
				isFirst = false;
			}

			super.onPageFinished(view, url);

		}
	}

	private class MyJavaScriptInterface {

		@SuppressWarnings("unused")
		public void showHTML(final String html) {

			setItem(html);

		}
	}

	public void setItem(String html) {

		boolean isItemsStart = false;
		boolean makingItem = false;
		boolean makingToonItem = false;
		int idxMakeItem = 0;
		ImageItem lImgItem = null;
		mToonItem = new ToonItem();

		for (String lll : html.split("\n")) {
			if (lll.trim().startsWith("\"images\"")) {
				isItemsStart = true;
				mToonItem.images = new ArrayList<ImageItem>();
			}

			if (!isItemsStart) {

				if (makingToonItem) {
					idxMakeItem++;
					switch (idxMakeItem) {

						case 1:
//							mToonItem.id = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 2:
							mToonItem.title = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 3:
//							mToonItem.id = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 4:
//							mToonItem.id = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 5:
//							mToonItem.id = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 6:
//							mToonItem.id = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 7:
//							mToonItem.id = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;

						default:
							break;
					}
				}

				if (lll.trim().startsWith("\"id\"")) {
					mToonItem.id = lll.trim().replace("\"", "").replace(":", "").replace(",", "").replace("id", "");
					;
					ToonItem lTi = (ToonItem) FileManager.loadObj(getApplicationContext(), FileManager.TOONSPATH, mToonItem.id + ".tit");

					if (lTi != null) {
						mToonItem = lTi;
						startActivity(new Intent(MainActivity2.this, MainActivity3.class).addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT));
						finish();
						return;
					} else
						FileManager.MakeToonFolder(getApplicationContext(), mToonItem.id);

					makingToonItem = true;
					idxMakeItem = 0;
				}
			} else {
				if (makingItem) {
					idxMakeItem++;
					switch (idxMakeItem) {
						case 1:
							lImgItem.url = lll.trim().replace("\"url\":\"", "").replace("\"", "").replace(",", "");
							downLoadThumb(lImgItem.url);
							break;
						case 2:
							lImgItem.key = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 3:
							lImgItem.imageOrder = Integer.parseInt(lll.trim().split(":")[1].replace("\"", "").replace(",", ""));
							break;
						case 4:
							lImgItem.mediaType = lll.trim().split(":")[1].replace("\"", "").replace(",", "");
							break;
						case 5:
							lImgItem.width = Integer.parseInt(lll.trim().split(":")[1].replace("\"", "").replace(",", ""));
							break;
						case 6:
							lImgItem.height = Integer.parseInt(lll.trim().split(":")[1].replace("\"", "").replace(",", ""));
							mToonItem.images.add(lImgItem);
							makingItem = false;
							break;
						default:
							break;
					}
				}
				if (lll.trim().startsWith("\"id\"")) {
					lImgItem = new ImageItem();
					lImgItem.id = lll.trim();
					makingItem = true;
					idxMakeItem = 0;
				}
			}

		}
		if (mToonItem != null && mToonItem.images != null && mToonItem.images.size() > 0) {
			FileManager.saveObj(getApplicationContext(), mToonItem, FileManager.TOONSPATH, mToonItem.id + ".tit");
			startActivity(new Intent(MainActivity2.this, MainActivity3.class).addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT));
			finish();
		}
	}

	public void fillList() {
		if (mToonItem != null && mToonItem.images != null && mToonItem.images.size() > 0) {

			new Handler().post(new Runnable() {

				@Override
				public void run() {
					mListView.invalidate();
				}
			});

		}
	}

	public void downLoadThumb(final String url) {
		try {

			String lFileName = makeFileName(url);
			File lTempFile = null;
			String path = FileManager.BASEPATH + getApplicationContext().getPackageName() + FileManager.TOONSPATH + "/" + mToonItem.id;

			String extState = Environment.getExternalStorageState();

			if (extState.equals(Environment.MEDIA_MOUNTED)) {
				File lPath = new File(path);
				if (!lPath.exists())
					lPath.mkdirs();

				lTempFile = new File(path, lFileName);
				if (lTempFile.exists())
					return;
			}
			URL lurl = new URL(url);
			URLConnection conn = lurl.openConnection();
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			final Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();

			saveFile(bm, lFileName);

		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
	}

	private String makeFileName(String aUrl) {
		String[] returnStrs = aUrl.split("/");
		return returnStrs[returnStrs.length - 1] + ".jpg";
	}

	private void saveFile(Bitmap bitmap, String fileName) {
		File lTempFile = null;

		String path = FileManager.BASEPATH + getApplicationContext().getPackageName() + FileManager.TOONSPATH + "/" + mToonItem.id;

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);

			FileOutputStream out;

			try {
				out = new FileOutputStream(lTempFile);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	}

}
